package io.yunho.srw.pwebflux.routerfunction.handler;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

/**
 * @author: yunho
 * @date: 2021/5/14 14:08
 * @description:
 */
@Component
//由于webException 有多个异常处理的handler 如果要让我们的异常处理生效 需要把优先级调高
@Order(-1)
@Configuration
public class ExceptionHandler implements WebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        ServerHttpResponse response = serverWebExchange.getResponse();
        //设置400响应头
        response.setStatusCode(HttpStatus.BAD_REQUEST);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
        //处理异常
        String errMsg = toStr(throwable);
        DataBuffer db = response.bufferFactory().wrap(errMsg.getBytes());
        return response.writeWith(Mono.just(db));
    }

    private String toStr(Throwable throwable) {
        //已知异常
        //这里当然是需要按照实际业务需要 定义异常对象来处理 这里只是拿OOM来充数的
        if(throwable instanceof RouterException){
            //已知异常可以简单处理
            return throwable.toString();
        }
        //未知异常 需要打印堆栈，方便定位
        else {
            throwable.printStackTrace();
            return throwable.toString();
        }
    }
}
